﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using Citi.FinancePlanningAnalysis.Domain;
using Citi.FinancePlanningAnalysis.SchedulerUi.SchedulerWcf;
using Citi.RoutineBase;

namespace Citi.FinancePlanningAnalysis.SchedulerUi
{
    public class CrcImport : GeneralImport
    {
        public new IEnumerable<RoutineParameter> Parameters
        {
            get
            {
                return new List<RoutineParameter> { 
                    new RoutineParameter{ Description = "If you want to start a routine when it's finished, insert the Routine Id.", 
                        Name ="SuccessorRoutineId", Nullable = true, Required = false, Type = typeof(int)}
                };
            }
        }

        public override string ExcelPath { get { return ConfigurationManager.AppSettings["CrcExcelPath"]; } }
        public override List<string> Files { get; set; }
        public override string QueryMergeDate { get { return Crc.QueryMergeDate; } }
        public override string QueryDeletePrevious { get { return Crc.QueryDeletePrevious; } }
        public override string QueryExcel { get { return Crc.QueryExcel; } }
        public override string TableTemp { get { return "CrcTemp"; } }
        public override Dictionary<string, string> ExcelColumnMappings { get { return Crc.ExcelColumnMappings; } }
        public override string SheetName { get { return "Sheet1"; } }

        public override void PrepareFiles(DateTime scheduledDate, RoutineBase.ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            currentAction.Description = string.Format("Looking for file in {0}", ExcelPath);
            Files = Directory.GetFiles(ExcelPath).Where(x => x.EndsWith(".xlsx")).ToList();
        }

        public override void FinishImport(ICurrentAction currentAction, Dictionary<string, object> parameters)
        {
            var successorRoutineId = parameters.ContainsKey("SuccessorRoutineId") ? parameters["SuccessorRoutineId"].ToString() : null;

            if (!string.IsNullOrWhiteSpace(successorRoutineId))
                SetSucessorRoutine(int.Parse(successorRoutineId), currentAction);
        }

        private void SetSucessorRoutine(int successorRoutineId, ICurrentAction currentAction)
        {
            if (successorRoutineId <= 0) return;

            currentAction.Description = "Scheduling successor routine";

            using (var client = new ScheduleClient())
                client.ExecuteRoutineOnDemandById(successorRoutineId, null);

            currentAction.Description = "Successor routine scheduled. It will be executed as soon as possible";
        }
    }
}
